package cn.tedu._05article.controller;

import cn.tedu._05article.base.response.JsonResult;
import cn.tedu._05article.base.response.StatusCode;
import cn.tedu._05article.mapper.UserMapper;
import cn.tedu._05article.pojo.dto.UserArticleParam;
import cn.tedu._05article.pojo.dto.UserLoginParam;
import cn.tedu._05article.pojo.entity.Article;
import cn.tedu._05article.pojo.vo.ArticleVO;
import cn.tedu._05article.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Validated
@RestController
@Tag(name = "01-用户模块")
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @Operation(summary = "1.用户登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam = " + userLoginParam);
        UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //将用户信息保存到session中
        session.setAttribute("user", userVO);
        return JsonResult.ok(userVO);
    }

    /**
     * 2.发表文章功能
     */
    @PostMapping("article")
    @Operation(summary = "2.发表文章功能")
    @ApiOperationSupport(order = 20)
    public JsonResult addArticle(@Validated @RequestBody UserArticleParam userArticleParam, HttpSession session){
        log.debug("userArticleParam = " + userArticleParam);
        UserVO userVO = (UserVO) session.getAttribute("user");
        //登录状态校验使用拦截器实现
//        if (userVO == null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        //登录状态
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);

        return JsonResult.ok();
    }

    /**
     * 3.查询指定文章功能
     */
    @GetMapping("selectByArticleId")
    @Operation(summary = "3.查询指定文章功能")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章ID必须在1-100之间") Long id){
        log.debug("id = " + id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);

        return JsonResult.ok(articleVO);
    }
}












